package com.example.demo3.controller;

import com.example.demo3.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RequestMapping("/file")
@Api("文件上传")
@RestController
public class FileController {

    @Value("${upload.filePath}")
    private String filePath;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result register(@RequestParam("file") MultipartFile file){

        // 判断文件是否为空
        if (file == null) {
            return new Result(500,"文件为空，请重新上传",null);
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件扩展名
        String fileExtension = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        // 重新生成的文件名
        String saveFileName = System.currentTimeMillis() + fileExtension;
        //创建一个文件对象
        File directory = new File(filePath);
        //查看此目录是否有该文件夹
        if (!directory.exists()){
            directory.mkdir();//创建文件夹
        }
        // 在指定目录下创建该文件

        try {
            File targetFile = new File(filePath, saveFileName);
            file.transferTo(targetFile);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return  new Result(200,"上传成功,返回图片地址","/images/"+saveFileName);
    }
}